<template>
    <div class="home">
        <!--banner-->
        <div class="home-banner">
            <!--定位 和 消息-->
            <div class="home-header">
                <span>
                    <router-link tag="span" to="/f-position">
                        <i class="iconfont icon-location"></i>
                        <span v-text="cityName" class="city-name"></span>
                    </router-link>
                </span>
                <span>
                    <i @click="jumporNo" class="iconfont icon-comment"></i>
                    <span v-show="showReddot" class="vux-reddot"></span>
                </span>
            </div>
            <!--banner-->
            <HomeBanner :lists="indexBanner" @indexJump="indexJump"></HomeBanner>
        </div>
        <!--产品分类-->
        <div class="product-type">
            <div class="type-item" @click="handleProductTypeJump(0)">
                <span class="speed">
                    <i class="iconfont icon-index-extreme"></i>
                </span>
                <p>极速贷款</p>
            </div>
            <div class="type-item" @click="handleProductTypeJump(1)">
                <span class="bank">
                    <i class="iconfont icon-index-bank"></i>
                </span>
                <p>银行贷款</p>
            </div>
            <div class="type-item" @click="handleProductTypeJump(2)">
                <span class="credit">
                    <i class="iconfont icon-index-card"></i>
                </span>
                <p>信用卡</p>
            </div>
        </div>
        <FSpace type="small"></FSpace>
        <!--通知-->
        <Notice :lists="noticeList" v-if="noticeList.length" @indexJump="indexJump"></Notice>
        <FSpace type="small" v-if="noticeList.length"></FSpace>
        <!--额度评估与贷款计算器-->
        <div class="calculator-assessment">
            <div class="calculator-item vux-1px-r" @click="handleAssessmentJump">
                <img onclick="return false" src="../../assets/img/assessment.png" alt="">
            </div>
            <div class="calculator-item" @click="handleCalculatorJump">
                <img onclick="return false" src="../../assets/img/calculator.png" alt="">
            </div>
        </div>
        <FSpace type="small"></FSpace>
        <!--活动专区-->
        <FBlockTitle title="活动专区" v-if="activityList.length"></FBlockTitle>
        <ul class="activity-area" v-if="activityList.length">
            <li v-for="(i,index) in activityList" :key="index">
                <img :src="i.context" alt="i.name" @click="indexJump(i)">
            </li>
        </ul>
        <!--footer-->
        <FSpace type="small" v-if="activityList.length"></FSpace>
        <!--为你优选-->
        <FBlockTitle title="为你优选" v-if="prodList.length"></FBlockTitle>
        <FProdList :lists="prodList" @on-click-prodItem="handleProductJump" v-if="prodList.length"></FProdList>
        <FSpace type="small" v-if="prodList.length"></FSpace>
        <!--信用卡专栏-->
        <canvas id="defaultIMG" style="display: none;" width="750" height="388"></canvas>
        <FBlockTitle title="信用卡专栏" v-if="creditList.length"></FBlockTitle>
        <div class="credit-swipe-box" v-if="creditList.length >= 1">
            <swiper :options="swiperOption" ref="mySwiper" @click="handleSwiper">
                <swiperSlide v-for="(i,index) in creditList" :key="index">
                    <img :src="i.context">
                </swiperSlide>
            </swiper>
        </div>
        <FSpace type="large"></FSpace>
        <FFooter :index="0"></FFooter>
    </div>
</template>

<script>
/**
 * Created by c.y on 2018/3/16.
 * 首页
 */
import { cookie } from 'vux';
import FFooter from '../../components/common/FFooter.vue';
import FBlockTitle from '../../components/common/FBlockTitle.vue';
import FProdList from '../../components/common/FProdList.vue';
import FSpace from '../../components/common/FSpace.vue';
import HomeBanner from '../../components/HomeBanner.vue';
import { swiper, swiperSlide } from 'vue-awesome-swiper';
import Notice from '../../components/Notice.vue';
import SysApi from '../../api/api';
import statusCodeManage from '../../api/statusCodeManage';

export default {
    name: 'f-main',
    components: {
        FFooter,
        FBlockTitle,
        FProdList,
        FSpace,
        swiper,
        swiperSlide,
        Notice,
        HomeBanner,
        cookie,
    },
    data() {
        return {
            //模态窗
            showModal: false,
            modalContent: '你需要登录哦',
            comfirmText: '登陆',
            cancelText: '下次吧',
            showReddot: false,
            cityName: '', // 当前城市名称
            cityCode: null, // 当前城市code
            indexBanner: [], //首页最上方的banner
            noticeList: [], //通知
            creditList: [], //信用卡专区
            activityList: [],
            prodList: [], // 产品列表
            showNone: false, //产品列表空白页
            swiperOption: {
                // swiper的配置
                autoplay: {
                    delay: 3000,
                    disableOnInteraction: false
                },
                spaceBetween: 10,
                slidesPerView: 'auto',
                centeredSlides: true,
                loop: true,
                observeParents: true,
                notNextTick: true,
                observer: true
            }
        };
    },
    computed: {
        swiper() {
            return this.$refs.mySwiper.swiper;
        }
    },
    methods: {
        handleSwiper() {
            let activeIndex;
            // 没有重复
            if (this.swiper.activeIndex <= this.creditList.length) {
                activeIndex = this.creditList.length - this.swiper.activeIndex;
            } else {
                activeIndex = this.creditList.length * 2 - this.swiper.activeIndex;
            }
            if (activeIndex !== 0) {
                activeIndex = this.creditList.length - activeIndex;
            }
            this.indexJump(this.creditList[activeIndex]);
        },
        // 更新城市code cityCode为发送请求的code
        updateCityCode(cityCode) {
            // 全局发送城市code
            let newClientInfo = JSON.parse(
                window.localStorage.getItem('newClientInfo')
            );
            newClientInfo.areaCode = cityCode;
            window.localStorage.setItem(
                'newClientInfo',
                JSON.stringify(newClientInfo)
            );
        },
        // 调取高德地图api, 获取cityCode与cityName
        fetchCityCodeByGao() {
            let _this = this;
            // 创建地图对象需要一个div对象id为geolocation
            let mapObj = new AMap.Map('homeGeolocation');
            // 使用城市搜索组件
            mapObj.plugin('AMap.Geolocation', function() {
                // AMap.Geolocation    AMap.CitySearch
                let geolocation = new AMap.Geolocation({
                    // Geolocation
                    enableHighAccuracy: false, //是否使用高精度定位，默认:true
                    GeoLocationFirst: false, // 默认为false，设置为true的时候可以调整PC端为优先使用浏览器定位，失败后使用IP定位
                    timeout: 10000, //超过10秒后停止定位，默认：无穷大
                    maximumAge: 0, //定位结果缓存0毫秒，默认：0
                    showButton: false, // 是否显示定位按钮
                    useNative: false // 是否使用安卓定位sdk用来进行定位
                    // enableHighAccuracy: true, //是否使用高精度定位，默认:true
                    // timeout: 10000,          //超过10秒后停止定位，默认：无穷大
                    // maximumAge: 0,           //定位结果缓存0毫秒，默认：0
                    // showButton: false,        //显示定位按钮，默认：true
                });
                // getCurrentPosition   getLocalCity
                // 定位失败的次数，我们约定为3次，3次失败的话，就展示获取城市失败
                let posiTimes = 3;
                _this.getGeolocation(geolocation, posiTimes);
            });
        },
        // 高德地图调取api
        getGeolocation(geolocation, posiTimes) {
            let _this = this;
            geolocation.getCurrentPosition(function (status, result) {
                posiTimes--;
                // 定位成功
                if (status == 'complete') {
                    _this.cityName = result.addressComponent.city;
                    _this.cityCode = result.addressComponent.adcode;
                    _this.cityCode =
                        _this.cityCode.substring(0, _this.cityCode.length - 2) +
                        '00';
                    let cityCodeObj = {
                        name: _this.cityName,
                        code: _this.cityCode
                    };
                    window.localStorage.setItem(
                        'cityCode',
                        JSON.stringify(cityCodeObj)
                    );
                    _this.updateCityCode(_this.cityCode);
                    // 重新调取api,渲染首页
                    _this.init();
                    return false;
                } else {
                    // 定位失败，一直重复定位,如果3次之后，那么就不在定位，直接展示定位失败
                    // 定位失败后，还是传递成都code，只是上面的城市的显示为定位失败
                    if (!posiTimes) {
                        _this.cityName = '定位失败';
                        //                            _this.init();
                        return false;
                    } else {
                        // 用户拒绝定位，传递成都code
                        if (
                            result.message === 'Geolocation permission denied.'
                        ) {
                            _this.cityName = '定位失败';
                            //                                _this.init();
                            return false;
                        } else {
                            // 如果是其他原因造成的定位失败的话，我们尝试三次定位，如何失败的话
                            // 默认传递成都code，显示定位失败
                            _this.getGeolocation(geolocation, posiTimes);
                        }
                    }
                }
            });
        },
        indexJump(item) {
            switch (item.type) {
                case 1:
                    //跳转到对应的导航页面
                    this.$router.push({path: item.detailContent});
                    break;
                case 2:
                    //跳转到对应的贷款分类
                    this.$router.push({path: item.detailContent});
                    break;
                case 3:
                    //跳转到贷款详情，需要产品ID
                    if (item.prodTypeId === 40000005) {
                        this.$router.push({
                            path: '/f-loan-detail',
                            query: {id: item.detailContent}
                        });
                    } else if (item.prodTypeId === 40000006) {
                        this.$router.push({
                            path: '/f-loan-detail',
                            query: {id: item.detailContent}
                        });
                    } else if (item.prodTypeId === 40000007) {
                        this.$router.push({
                            path: '/f-credit-detail',
                            query: {id: item.detailContent}
                        });
                    }
                    break;
                case 4:
                    //第三方页面
                    window.location.href = item.detailContent;
                    break;
                case 5:
                    //什么都不做
                    break;
                case 6:
                    //资讯
                    this.$router.push({path: '/f-news-detail',query:{id:item.detailContent}});
                    break;
                default:
                    break;
            }
        },
        /**
         * 页面初始化 获取定位
         */
        initCityCode: function () {
            let _this = this;
            // 如果本地有城市数据 ，就不需要去请求
            let _cityCode = window.localStorage.getItem('cityCode');
            // 本地有cityCode的话
            if (_cityCode) {
                _cityCode = JSON.parse(_cityCode);
                _this.cityName = _cityCode.name;
                _this.cityCode = _cityCode.code;
                // 页面的初始化
                _this.init();
                return false;
            } else {
                // cityCode默认是成都的，先使用默认的成都code的话，调取后台后台首页
                // 等调取高德地图的api返回code，再调取后台的重新渲染首页的
                _this.cityName = '定位中';
                _this.init();
                _this.fetchCityCodeByGao();
            }
        },
        // 处理产品跳转
        handleProductJump(item) {
            // 极速贷款或者银行卡
            if (
                item.productType === 40000005 ||
                item.productType === 40000006
            ) {
                this.$router.push({
                    path: '/f-loan-detail',
                    query: {
                        id: item.prodId
                    }
                });
                // 信用卡
            } else if (item.productType === 40000007) {
                this.$router.push({
                    path: '/f-credit-detail',
                    query: {
                        id: item.prodId
                    }
                });
            }
        },
        // 产品分类的跳转
        handleProductTypeJump(typeId) {
            if (typeId === 0) {
                this.productTypeJump('/f-loan/f-speed', typeId);
            } else if (typeId === 1) {
                this.productTypeJump('/f-loan/f-bank', typeId);
            } else if (typeId === 2) {
                this.productTypeJump('/f-loan/f-credit', typeId);
            }
        },
        // 分类跳转
        productTypeJump(path, typeId) {
            this.$router.push({
                path: path,
                query: {
                    typeId: typeId
                }
            });
        },
        toConfirm() {
            this.$router.push({name: 'f-login'});
        },
        // 额度计算跳转--这个需要用户登录，如果未登录跳转login
        handleAssessmentJump() {
            // 判断是否登录
            let _newSid = window.sessionStorage.getItem('newSid');
            if (_newSid) {
                // 登录跳转
                this.$router.push({path: '/f-assessment'});
            } else {
                // 跳转到登录界面
                // 记录当前地址
                window.sessionStorage.setItem(
                    'newGoBackPage',
                    window.location.hash.split('#')[1]
                );
                this.$router.push({path: '/f-login'});
            }
        },
        // 贷款计算器跳转--这个需要用户登录，如果未登录跳转login
        handleCalculatorJump() {
            // 判断是否登录
            let _newSid = window.sessionStorage.getItem('newSid');
            if (_newSid) {
                // 登录跳转
                this.$router.push({path: '/f-compute'});
            } else {
                // 跳转到登录界面
                // 记录当前地址
                window.sessionStorage.setItem(
                    'newGoBackPage',
                    window.location.hash.split('#')[1]
                );
                this.$router.push({path: '/f-login'});
            }
        },
        // 获取Attr的列表, prodElements产品组件的元素列表
        getAttrList(prodElements) {
            // 获取用户修改的数据
            let attrList = [];
            if (prodElements instanceof Array) {
                prodElements.map(function (listItem) {
                    listItem.attrs.forEach(function (item) {
                        attrList.push(item.value);
                    });
                });
            }
            return attrList;
        },
        // 页面的初始化
        init() {
            let _this = this;
            let _newSid = window.sessionStorage.getItem('newSid');
            let _newClientInfo = window.sessionStorage.getItem('newClientInfo');
            if (_newSid == null) {
            }
            SysApi.homeInit().then(
                res => {
                    _this.prodList = [];
                    _this.indexBanner = res.body.indexBanner;
                    _this.noticeList = res.body.announcement;
                    _this.creditList = res.body.creditCardBanner;
                    _this.activityList = res.body.activityBanner;
                    cookie.set('ecImageCodeNum', res.body.imageCodeNum);
                    res.body.pushProductInfos.forEach(function (item) {
                        _this.prodList.push({
                            prodId: item.unit.prodId,
                            content: _this.getAttrList(item.showEles),
                            productType: item.unit.prodType,
                            applyNumber:
                            item.unit.showNumPrefix + item.unit.showNum
                        });
                    });
                },
                err => {
                    statusCodeManage.showTipOfStatusCode(err, this);
                }
            );
            // 获取消息
            SysApi.homeNotice().then(
                res => {
                    // 回调成功后的函数
                    let sid = window.sessionStorage.getItem('newSid');
                    if (!sid) {
                        _this.showReddot = false;
                        window.sessionStorage.setItem('unRead', '[]');
                        return false;
                    }
                    if (res.body.length) {
                        _this.showReddot = true;
                        window.sessionStorage.setItem(
                            'unRead',
                            JSON.stringify(res.body)
                        );
                    } else {
                        window.sessionStorage.setItem('unRead', '[]');
                        _this.showReddot = false;
                    }
                },
                error => {
                    // 回调失败的函数
                    statusCodeManage.showTipOfStatusCode(error, this);
                }
            );
        },
        // 判断点击是否跳转到消息页面
        jumporNo() {
            this.$router.push({path: '/f-message-center'});
        }
    },
    activated: function() {
        this.indexBanner = [];
        this.noticeList = [];
        this.activityList = [];
        this.prodList = [];
        // 初始化页面方法获取当前城市
        // 把数据清空放在activated,不放在deactivated里面，由于渲染能力弱
        // 的是手机，点击跳转页面时，deactivated数据清空，导致dom不存在，
        // 而此时页面还没有跳转，看到的内容是初始化没有什么内容的值，样式结构不一致
        let canvObj = document.getElementById('defaultIMG');
        let cxt = canvObj.getContext('2d');
        var grd = cxt.createLinearGradient(0, 0, 0, 388);
        grd.addColorStop(0, '#f1f1f1');
        grd.addColorStop(1, '#999');
        cxt.fillStyle = grd;
        cxt.fillRect(0, 0, 750, 388);
        // 创建默认图片
        this.indexBanner = [
            {
                context: canvObj.toDataURL(),
                detailContent: '',
                id: 21,
                name: '默认图',
                place: 1,
                prodTypeId: null,
                sysType: 1,
                type: 2
            }
        ];
        this.initCityCode();
        if (this.$refs.mySwiper) {
            this.$refs.mySwiper.swiper.slideTo(1, 100, false);
        }
    }
}
</script>
<style lang="less">
@import '../../style/mixin';
@import '../../style/swiper.min.css';

.weui-dialog__btn_primary {
    color: @color-primary !important;
}

.product-type .iconfont {
    font-size: 18px;
}

.swipe-box {
    box-sizing: border-box;
    padding: 10px 0;
    .swiper-container {
        padding-left: 50px;
    }
}

.home-banner {
    position: relative;
    .home-header {
        position: absolute;
        left: 0;
        top: 0;
        .flexLayout();
        box-sizing: border-box;
        width: 100%;
        height: 44px;
        padding: 0 12px;
        font-size: @font-size-primary;
        line-height: 44px;
        z-index: 1000;
        color: #fff;
        vertical-align: middle;
        .city-name {
            display: inline-block;
            text-align: left;
            .ellipsis(70px);
            font-size: 14px;
            vertical-align: bottom;
        }
        .icon-comment {
            font-size: 20px;
        }
        span {
            flex: 1;
            &:last-child {
                text-align: right;
            }
            .city-name {
                text-align: left;
            }
        }
    }
    .swiper-slide {
        width: 100%;
        height: 190px;
        img {
            width: 100%;
            height: 190px;
        }
    }
}

.product-type {
    .flexLayout();
    box-sizing: border-box;
    padding: 20px 0 10px;
    .type-item {
        flex: 1;
        text-align: center;
    }
    span {
        display: inline-block;
        width: 44px;
        height: 44px;
        line-height: 44px;
        color: #fff;
        border-radius: 50%;
    }
    .iconfont {
        font-size: 20px;
    }
    .speed {
        .color-linear-gradient(@color-gradient-darkBlue-left, @color-gradient-darkBlue-right);
        .icon-index-extreme {
            display: inline-block;
        }
    }
    .bank {
        .color-linear-gradient(@color-gradient-red-left, @color-gradient-red-right);
    }
    .credit {
        .color-linear-gradient(@color-gradient-lightBlue-left, @color-gradient-lightBlue-right);
    }
    P {
        font-size: @font-size-medium;
        line-height: 34px;
        color: @color-text-primary;
    }
}

.calculator-assessment {
    height: 70px;
    .flexLayout();
    .calculator-item {
        width: 50%;
        img {
            width: 100%;
            border: 0;
            display: block;
        }
    }
}

.activity-area {
    width: 100%;
    padding: 10px 0 12px 0;
    font-size: 0;
    list-style: none;
    overflow-x: scroll;
    white-space: nowrap;
    box-sizing: border-box;
    &::-webkit-scrollbar {
        display: none;
    }
    li {
        display: inline-block;
        width: 160px;
        height: 84px;
        margin-left: 10px;
        border-radius: @border-radius-normal-size;
        overflow: hidden;
        &:last-child {
            margin-right: 10px;
        }
    }
    a {
        display: block;
        cursor: pointer;
        text-decoration: none;
        -webkit-tap-highlight-color: rgba(0, 0, 0, 0);
    }
    img {
        display: inline-block;
        width: 160px;
        height: 84px;
    }
}

.credit-swipe-box {
    width: 100%;
    padding: 10px 0;
    height: 170px;
    box-sizing: border-box;
    .swiper-wrapper {
        align-items: center;
    }
    .swiper-slide {
        width: 300px;
        height: 120px;
        text-align: center;
        border-radius: @border-radius-normal-size;
        transition: height 0.4s;
        img {
            width: 300px;
            height: 100%;
            transition: all 0.4s;
            border-radius: @border-radius-normal-size;
        }
    }
    .swiper-slide-active {
        width: 300px;
        height: 150px;
    }
}
</style>
